<template>
  <basic-dialog
    width="70%"
    title="授权品类"
    :visible="visible"
    :showClose="isView"
    :handleClose="handleClose"
  >
    <el-row type="flex">
      <div class="form-item">
        <span class="form-item-label">非金属制品品类授权：</span>
        <el-select
          v-model="categoryLevel"
          placeholder="请选择"
          clearable
          :disabled="isView"
          @change="handleSelectChange"
        >
          <el-option
            v-for="item in options.categoryLevel"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="form-item">
        <span class="form-item-label">
          <span class="red_star">*</span>
          是否金属制品授权：
        </span>
        <el-select
          v-model="isMetal"
          placeholder="请选择"
          clearable
          :disabled="isView"
        >
          <el-option
            v-for="item in options.isMetal"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
    </el-row>
    <el-row class="search-wrap">
      <div class="form-item">
        <span class="form-item-label">模糊搜索当前级别分类：</span>
        <el-input
          class="search-input"
          v-model="queryString"
          placeholder="请输入搜索内容"
          @keyup.enter.native="handleInputFilter(queryString)"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-refresh search-btn"
            @click.stop="handleInputFilter('')"
          />
          <i
            slot="suffix"
            class="el-input__icon el-icon-search search-btn"
            @click.stop="handleInputFilter(queryString)"
          />
        </el-input>
      </div>
    </el-row>
    <el-divider content-position="left">
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        :disabled="isView"
        @change="handleCheckAllChange" />
      <span class="check-label">全选</span>
    </el-divider>
    <div class="list-wrap">
      <el-checkbox-group
        v-model="checkedCodeList"
        :disabled="isView"
        @change="handleCheckeChange"
      >
        <el-checkbox
          v-for="item in categoryList"
          :key="item.uuid"
          :label="item.uuid"
        >
          <span>{{ `${item.categoryNo} ${item.categoryName}` }}</span>
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <el-row v-show="!isView" slot="ft" type="flex" justify="center">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="okLoading" @click="handleOk">确定</el-button>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import { CATE_LEVEL_OPTIONS, METAL_OPTIONS, METAL_VALUES } from '../constants';
import { getCategoryService } from '@/api/usercenter';
import { authService } from '@/api/commodity/departmentManage/departmentManage';
export default {
  components: {
    BasicDialog,
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    echoInfos: {
      type: Object,
      default: () => ({})
    },
    isView: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      categoryLevel: '',
      isMetal: '',
      okLoading: false,
      options: {
        categoryLevel: [...CATE_LEVEL_OPTIONS].slice(0, 3),
        isMetal: METAL_OPTIONS
      },
      checkAll: false,
      isIndeterminate: false,
      checkedCodeList: [],
      categoryList: [],
      cateListMaps: new Map(),
      queryString: '',
      originalCateList: []
    }
  },
  watch: {
    visible (val) {
      if (!val) return
      this.setEchoCateList()
      !this.isView && this.getCategoryByLevel()
    }
  },
  methods: {
    handleInputFilter (queryString) {
      this.queryString = queryString
      const reg = new RegExp(queryString)
      this.categoryList = this.originalCateList.filter(item => reg.test(item.categoryName))
    },
    // 设置查看品类集合
    setEchoCateList () {
      const { levenNum: levelNum = '', isMetal = '', categories = [] } = this.echoInfos
      this.categoryList = [...categories]
      this.checkedCodeList = [...categories.map(item => item.uuid)]
      this.categoryLevel = levelNum == 0 ? '' : levelNum
      this.isMetal = isMetal
    },
    // 根据品类授权等级获取品类集合
    async getCategoryByLevel () {
      if (!this.categoryLevel) return
      const data = { levelNum: this.categoryLevel }
      const res = await getCategoryService(data, null, '.list-wrap')
      if (res?.retData) {
        this.categoryList = res.retData
        this.originalCateList = res.retData
        this.categoryList.forEach(item => {
          this.cateListMaps.set(item.uuid, item)
        })
      }
    },
    // 重置集合所有状态
    resetListAll () {
      this.checkAll = false
      this.isIndeterminate = false
      this.checkedCodeList = []
      this.cateListMaps = new Map()
      this.categoryList = []
    },
    // 确定
    handleOk () {
      if (!this.isMetal) return this.$message.warning('请选择是否金属制品授权')
      const hasNoChecked = this.checkedCodeList.length == 0
      // if (this.isMetal == METAL_VALUES.No && hasNoChecked) return this.$message.warning('非金属制品授权，请选择分类')
      const confirmWarn = () => {
        const content = '当前授权品类为空，确认要提交吗？'
        this.$confirm(content, '警告', {
          type: 'warning',
        }).then(() => {
          this.submitAuthInfo()
        }).catch(() => {})
      }
      hasNoChecked ? confirmWarn() : this.submitAuthInfo()
    },
    // 关闭弹框
    handleClose () {
      this.$emit('update:visible', false);
    },
    // 下拉change
    handleSelectChange () {
      this.resetListAll()
      this.getCategoryByLevel()
    },
    // 全选
    handleCheckAllChange (val) {
      this.isIndeterminate = false
      this.checkedCodeList = val ? this.categoryList.map(item => item.uuid) : []
      this.selectedList = val ? [...this.categoryList] : []
    },
    // 单选
    handleCheckeChange (list) {
      const checkedCount = list.length;
      this.checkAll = checkedCount === this.categoryList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.categoryList.length;
      this.selectedList = list
        .map(uuid => ({ ...this.cateListMaps.get(uuid) }))
        .filter(item => item)
    },
    // 提交认证信息
    async submitAuthInfo () {
      const categories = this.checkedCodeList.map(item => this.cateListMaps.get(item)).filter(item => item)
      const data = {
        categories,
        isMetal: this.isMetal,
        hrDepartmentId: this.echoInfos.departmentId
      }
      const loadingFn = state => { this.okLoading = state }
      const res = await authService(data, loadingFn)
      if (res.code == '0') {
        this.$message.success('提交成功')
        this.categoryLevel = ''
        this.isMetal = ''
        this.resetListAll()
        this.handleClose()
        this.$emit('updateTableData')
      }
    }
  }
}
</script>
<style lang="less" scoped>
.check-label {
  margin-left: 10px;
}
/deep/ .el-divider__text {
  left: -5px;
  padding: 0 5px;
}
.list-wrap {
  height: 400px;
  overflow: hidden;
  overflow-y: auto;
  /deep/ .el-checkbox {
    width: 275px;
    .el-checkbox__label {
      line-height: 16px;
      vertical-align: middle;
      span {
        width: 275px;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
.red_star {
  padding-top: 5px;
  color: #F56C6C;
}
.form-item {
  display: flex;
  align-items: center;
  &:nth-child(2) {
    margin-left: 20px;
  }
}
.form-item-label {
  width: 170px;
  text-align: right;
}

.search-wrap {
  margin-top: 10px;
  .search-input {
    width: 20.5%;
  }
  .search-btn {
    cursor: pointer;
    &:hover {
      color: #63a8fc;
    }
  }
}
</style>
